import wx
import os
import wx.lib.mixins.listctrl as listmix

class FileListCtrl(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin):
    """
    Extended ListCtrl to hold list of Image Files
    """
    def __init__(self, parent, ID, pos=wx.DefaultPosition,
                 size=wx.DefaultSize,model=None):
        wx.ListCtrl.__init__(self, parent, ID, pos, size,
             style=wx.LC_REPORT|wx.LC_SINGLE_SEL )
        listmix.ListCtrlAutoWidthMixin.__init__(self)
        self.InsertColumn(0,"Name",width=100)
        self.InsertColumn(1,"Source")
        self.imagelist = wx.ImageList(16,16)
        self.SetImageList(self.imagelist, wx.IMAGE_LIST_SMALL)
        self.iModel = model
        
    def Add(self,file):
        " Insert file into list of images to process"
        nolog=wx.LogNull() # Suppress invalid image message
        image=wx.Image(file,wx.BITMAP_TYPE_ANY)
        del nolog
        if not image.Ok(): 
            wx.MessageDialog(self,"Invalid image file \n"+file,
                     "File error",wx.OK|wx.ICON_ERROR).ShowModal()
            return  
        imx = self.imagelist.Add(wx.BitmapFromImage(image.Scale(16,16)))
        for name in makevarname(os.path.basename(file),
                  self.iModel.getOption("inclext",False)):
            if self.FindItem(-1,name) == -1:break 
        ix=self.GetFirstSelected()
        self.Select(ix,0)
        ix=self.InsertImageStringItem(ix+1,name,imx)
        self.SetStringItem(ix,1,file)
        self.iModel.setOption("cdir",os.path.dirname(file))
        self.iModel.doChange()
        self.Sel(ix)
        
    def Clear(self,iModel):
        self.iModel=iModel
        self.DeleteAllItems()
        
    def Delete(self):
        " Delete current selected item"
        ix = self.GetFirstSelected()
        if ix < 0 : return
        self.DeleteItem(ix)
        self.Sel(ix)
        
    def CanDelete(self):
        return(not self.GetFirstSelected() <0 )
            
    def MoveUp(self):
        " Move selected item up"
        ix = self.GetFirstSelected()
        if ix < 1 : return
        row = self.GetRow(ix)
        self.DeleteItem(ix)
        self.InsertRow(ix-1,row)
        self.Sel(ix-1)
        
    def CanMoveUp(self):
        return(not self.GetFirstSelected() < 1)    
        
    def MoveDown(self):
        " Move selected item down"
        ix = self.GetFirstSelected()
        if ix < 0 or ix >= self.GetItemCount()-1: return
        row = self.GetRow(ix)
        self.DeleteItem(ix)
        self.InsertRow(ix+1,row)
        self.Sel(ix+1)
        
    def CanMoveDown(self):
        ix = self.GetFirstSelected()
        return(not (ix < 0 or ix >= self.GetItemCount()-1))   
             
    def Sel(self,ix):
        if ix < 0 : ix=0
        if ix >= self.GetItemCount(): ix = self.GetItemCount()-1
        self.Select(ix)
        self.EnsureVisible(ix)
        
    def GetRow(self,ix):
        return [self.GetItem(ix,col) for col in range(self.GetColumnCount())]
        
    def InsertRow(self,ix,row):
        row[0].SetId(ix)
        self.InsertItem(row[0])
        
        for item in row[1:]:
            item.SetId(ix)
            self.SetItem(item)
    
    def GetFileList(self):
        return [(self.GetItem(ix,0).GetText(),self.GetItem(ix,1).GetText())
            for ix in range(self.GetItemCount())]
        
def makevarname(basename,useext):
    basesplit = os.path.splitext(basename)
    if useext: name=basesplit[0]+"_"+basesplit[1][1:]
    else: name=basesplit[0]
    # remove non alpanums
    name = "".join(c if c.isalnum() else "_" for c in name)
    # make sure starts with alpha
    if not name[0].isalpha(): name = "Z"+name
    yield name
    for i in xrange(1,1000):
        yield "%s_%d"%(name,i)